<template>
	<view class="page_content">
		<view class="main_content">
			<u-button :text="$t('payment.useStripe')" type="primary" :loading="loading" @click="payWithStripe" />
		</view>
	</view>
</template>

<script>
import { initStripe, redirectToCheckout } from '@/common/utils/stripe.js'
import { mapGetters } from 'vuex'
	export default {
		data() {
			return {
			loading: false,
			stripePk: this.$store.state.app.config?.stripe_pk || ''
			}
		},
	computed: {
		...mapGetters('user', ['token'])
	},
		methods: {
		async payWithStripe() {
			// 仅H5可用
			// #ifndef H5
			this.$u.toast(this.$t('payment.onlyH5'))
			return
			// #endif
			if(!this.token) return this.$u.toast(this.$t('userCenter.pleaseLogin'))
			if(!this.stripePk) return this.$u.toast(this.$t('payment.notConfigured'))
			try {
				this.loading = true
				await initStripe(this.stripePk)
				// 后端创建 Checkout Session
				const res = await this.$request('payment.stripeCreateSession', {
					// 可选：商品/金额/回调参数等，由后端决定
					channel: this.$store.state.app.channel || ''
				})
				if(res && res.code === 1 && res.data && res.data.id) {
					const result = await redirectToCheckout(res.data.id)
					if (result && result.error) {
						this.$u.toast(result.error.message || this.$t('payment.redirectFailed'))
					}
				} else {
					this.$u.toast(res.msg || this.$t('payment.sessionFailed'))
				}
			} catch (e) {
				console.error(e)
				this.$u.toast(this.$t('payment.startFailed'))
			} finally {
				this.loading = false
			}
		}
		}
	}
</script>

<style lang="scss" scoped>
.page_content {
	padding: 40rpx;
}
</style>
